package main

import (
	"context"
	"encoding/json"
	"log"
	"smartposts/internal/config"
	"smartposts/internal/global"
	"smartposts/internal/models"
	"smartposts/internal/mq"
	"smartposts/internal/utils"

	amqp "github.com/rabbitmq/amqp091-go"
	"github.com/redis/go-redis/v9"
)

func main() {
	// Initialize Config, DB, Redis, and MQ
	configPath := "./configs/config.yml"
	if err := config.LoadConfig(configPath); err != nil {
		log.Fatalf("failed to load config: %v", err)
	}

	config.InitDB()
	log.Println("Worker init database succeeded.")

	config.InitRedis()
	log.Println("Worker init redis succeeded.")
	defer global.RedisDB.Close()

	mq.InitMQ()
	log.Println("Worker init rabbitmq succeeded.")
	defer mq.MQ.Close()

	// Start consuming messages
	forever := make(chan bool)

	go consumeRankUpdate()

	log.Printf(" [*] Waiting for messages. To exit press CTRL+C")
	<-forever
}

func consumeRankUpdate() {
	q, err := mq.MQ.Channel.QueueDeclare(
		"rank.update", // name
		true,           // durable
		false,          // delete when unused
		false,          // exclusive
		false,          // no-wait
		nil,            // arguments
	)
	if err != nil {
		log.Fatalf("Failed to declare a queue: %s", err)
	}

	msgs, err := mq.MQ.Channel.Consume(
		q.Name, // queue
		"",     // consumer
		true,   // auto-ack
		false,  // exclusive
		false,  // no-local
		false,  // no-wait
		nil,    // args
	)
	if err != nil {
		log.Fatalf("Failed to register a consumer: %s", err)
	}

	for d := range msgs {
		log.Printf("Received a message: %s", d.Body)
		handleRankUpdate(d)
	}
}

func handleRankUpdate(d amqp.Delivery) {
	ctx := context.Background()

	var post models.Post
	if err := json.Unmarshal(d.Body, &post); err != nil {
		log.Printf("Error decoding message: %s", err)
		return
	}

	if err := global.RedisDB.ZAdd(ctx, "hot_posts",
		redis.Z{Score: utils.CompositeScore(post), Member: post.ID}).Err(); err != nil {
		log.Printf("Failed to update hot_posts for post %d: %v", post.ID, err)
		return
	}

	log.Printf("Successfully updated hot_posts for post %d", post.ID)
}